<!DOCTYPE html>
<html class="x-admin-sm">
{include file='public/header'}
<script src="/admin/xadmin/lib/layui/upload.js" charset="utf-8"></script>
<script src="/admin/xadmin/js/jquery.gridly.js?vension=1.0" charset="utf-8"></script>
<link rel="stylesheet" href="/admin/xadmin/css/jquery.gridly.css">
<style>
    .gridly {
        position: relative;
    }

    .moneyContent {
        padding: 15px 10px;
        border: 1px solid #c2c2c2;
        background-color: #fff;
    }

    .moneyContent .content {
        border: 1px solid #dcdcdc;
        padding: 10px 0
    }

    .moneyContent .content div {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .moneyContent .content .title {
        font-size: 24px;
    }

    .moneyContent .content .title,
    .moneyContent .content .startSet {
        margin-left: 10px;
    }

    .moneyContent .content .startSet i {
        color: #fa2a2d;
    }

    .moneyContent .content .tip {
        border-radius: 15px 0 0 15px;
        background-color: #fa2a2d;
        color: #fff;
        padding: 2px 8px;
        font-size: 12px;
    }

    .moneyContent .foot {
        display: flex;
        align-items: center;
        /* justify-content: flex-end; */
        justify-content: space-between;
        margin-top: 5px;
    }

    .layui-form-radio {
        margin: 0;
        font-size: 16px;
    }

    .layui-form-radio:hover *,
    .layui-form-radioed,
    .layui-form-radioed>i {
        color: #1e9fff;
    }

    .layui-row {
        display: flex;
        justify-content: center;
    }

    .btn {
        display: flex;
        justify-content: center;
        margin-top: 10px;
    }

    .moneyTemplate .layui-form-label {
        width: 95px;
        padding: 9px 5px;
    }

    .layui-layer-page .layui-layer-content {
        overflow: visible;
    }

    .layui-tab-content {
        padding-bottom: 0;
    }

    .item {
        display: flex;
        width: 80%;
    }

    .layui-input-block {
        margin-left: 165px;
        display: flex;
        align-items: center;
    }

    #selectAccount .layui-input-block {
        margin-left: 0;
    }

    .designated_amount_echo {
        width: 50%;
    }

    .designated_amount_echo .item {
        display: flex;
        justify-content: space-between;
        margin-top: 10px;
        height: 38px;
    }

    .designated_amount_echo .item div {
        display: flex;
        align-items: center;
    }

    .designated_amount_echo .item .content div {
        margin-right: 10px;
    }

    .designated_amount_echo .item input {
        flex: 1;
        width: 75px;
        height: 30px;
    }

    .designated_amount_echo .item .operate span {
        margin-right: 15px;
        display: inline-block;
        width: 20px;
        height: 20px;
        padding: 0;
        line-height: 20px;
    }

    .layui-form-label {
        width: 135px;
    }

    .fairy-tag {
        display: flex;
    }

    .fairy-tag-container {
        display: flex;
        flex-direction: column;
        align-items: flex-start;
    }

    #stages {
        width: 60%;
        display: flex;
        flex-direction: column;
        margin-left: 165px;
    }

    .stage {

        display: flex;
        align-items: center;

    }

    .layui-badge {}
</style>

<body>
    <div style="padding:0 20px">
        <form class="layui-form" lay-filter="formAjax">
            <div class="layui-form-item">
                <label class="layui-form-label">
                    <span class="x-red">*</span>模板名称
                </label>
                <div class="layui-input-block">
                    <input type="text" name="name" id="name" placeholder="充值模板名称" required="required"
                        lay-verify="required" autocomplete="off" class="layui-input" value="" />
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">
                    <span class="x-red">*</span>类型
                </label>
                <div class="layui-input-block" id='select-rebate'>
                    <select name="type" id="type">
                        <option value="">请选择</option>
                        <option value="1">低充</option>
                        <option value="2">中充</option>
                        <option value="3">高充</option>

                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">
                    <span class="x-red">*</span>剧名
                </label>

                <div id="pMenu" style="width:100%;"></div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">
                    <span class="x-red">*</span>开始收费剧集
                </label>
                <div class="layui-input-block">
                    <input type="number" name="sort" id="sort" placeholder="收费剧集" required="required|nums"
                        lay-verify="required" autocomplete="off" class="layui-input sort" value=""
                        onchange="onsort(this)" />
                </div>
            </div>
            
            <div class="layui-form-item" id="zhidhuichuan">
                <label class="layui-form-label">
                    <span class="x-red">*</span>每集收费K币
                </label>
                <div class="layui-input-block" style="display: flex;align-items: center;">
                    <input type="number" name="pay_amount" style="width: 80px;" class="layui-input payamount"
                        onchange="fixation()" />
                </div>

            </div>

            <div class="layui-form-item" id="zhidhuichuan">

            </div>
            <blockquote id="phone_tip" style="display: none;" class="layui-elem-quote">移动端暂不支持拖动模板！</blockquote>
            <div class="layui-tab" lay-filter="tabs">
                <ul class="layui-tab-title"> 米
                    <li class="layui-this" onclick="changeTag(1)">已充值用户</li>
                    <li onclick="changeTag(2)"> 未充值用户</li>
                </ul>
                <div class="layui-tab-content">
                    <div class="layui-tab-item layui-show">
                        <div class="layui-row">
                            <div class="layui-col-xs12 layui-col-md8 layui-col-space10 gridly" id="recharged_cont">
                                <!-- <div class="layui-col-xs6">
                                    <div class="moneyContent">
                                        <div class="content">
                                            <div>
                                                <span class="title">66元</span>
                                                <span class="tip">首充</span>
                                            </div>
                                            <div>
                                                <span class="startSet">
                                                    6600
                                                    <i>+4800K币</i>
                                                </span>
                                                <span class="tip" style="background-color: #f2f2f2;color:#000">全部用户</span>
                                            </div>
                                        </div>
                                        <div class="foot">
                                            <input type="radio" name="sex" value="1" title="默认勾选" checked="checked">
                                            <div>
                                                <i class="layui-icon layui-icon-edit" style="font-size: 24px;"></i>
                                                <i class="layui-icon layui-icon-delete" style="font-size: 24px;"></i>
                                            </div>
                                        </div>
                                    </div>
                                </div> -->

                            </div>
                        </div>
                        <div class="btn">
                            <button type="button" class="layui-btn" onclick="add(1)">添加商品</button>
                        </div>
                    </div>
                    <div class="layui-tab-item">
                        <div class="layui-row">
                            <div class="layui-col-xs12 layui-col-md8 layui-col-space10 gridly" id="not_recharged_cont">

                            </div>
                        </div>
                        <div class="btn">
                            <button type="button" class="layui-btn" onclick="add(2)">添加商品</button>
                        </div>
                    </div>
                </div>
            </div>


            <input type="hidden" name="id" id="id" value="" />

            <input type="hidden" name="recharged_content" id="recharged_content" value="" />
            <input type="hidden" name="not_recharged_content" id="not_recharged_content" value="" />
            <!-- <input type="hidden" name="video"  value="" /> -->
            <input type="hidden" name="interval_recharge" id="interval_recharge" lay-verify="interval_recharge">

            <button id="submitData" class="layui-btn" lay-submit lay-filter="submitData" style="display: none;" />

        </form>
    </div>
    <script>
        let params = {
            addUrl: '/cps/customRechargeTemplate/add',
            editUrl: '/cps/customRechargeTemplate/edit',
            detailUrl: '/cps/customRechargeTemplate/detail',
            hasCallback: false
        }
        form_ajax(params)
        let phone = false
        if (os.isAndroid || os.isPhone) {
            phone = true
            $('#phone_tip').show()
        }
        // 获取缓存中的数据
        let rc = JSON.parse(sessionStorage.getItem('recharged_content'))
        let nrc = JSON.parse(sessionStorage.getItem('not_recharged_content'))
        let rechargedIndex = 0;
        let not_rechargedIndex = 0;

        let interval_recharge = []  //阶梯
        // 金额回传

        let selectParams = {
            url: '/cps/video/select?is_shelves=0',
            selected: [],
            tips: '选择短剧',
            name: 'video_id',
            field_id: 'id',
            field_Name: 'name',
            elem: '#pMenu',
            disabled: GetQueryString('id') ? true : false
        }

        layui.use('form', function () {
            var form = layui.form;

            form.verify({
                nums: [
                    /^[1-9]\d*$/, '只能输入大于0的整数'
                ],

            });
            form.on('radio(recharge_template_id)', function (data) {
                $('#recharge').css('display', data.value === '-1' ? 'block' : 'none')
                selectParams2.selected = []
                selectN(selectParams2)
            });
            form.on('radio(charge_type)', function (data) {

                if (data.value === '1') {
                    // addStage()
                    let elements = document.querySelectorAll('.shoudon');
                    fixation()
                    elements.forEach(element => {

                        element.remove();

                    });
                } else {
                    calculate()
                }

                $('.item').css('display', data.value === '2' ? 'block' : 'none')
                $('.guding').css('display', data.value === '1' ? 'block' : 'none')
            });
            form.on('submit(submitData)', function (data) {


                if (data.field.charge_type == 2) {
                    var elements = document.querySelectorAll('.fee');

                    for (let i = 0; i < elements.length; i++) {
                        if (!elements[i].value) {
                            layer.msg('收费K币不合法，请输入合法的值！')
                            return false
                        } else if (parseInt(elements[i].value) < 0) {
                            layer.msg('收费K币不合法，请输入合法的值！')
                            return false
                        }

                    }

                    var elements1 = document.querySelectorAll('.start');

                    for (let i = 0; i < elements1.length; i++) {
                        if (!elements1[i].value) {
                            layer.msg('区间不能为空！')
                            return false
                        } else if (parseInt(elements[i].value) < 0) {
                            layer.msg('收费K币不合法，请输入合法的值！')
                            return false
                        }

                    }

                    var elements2 = document.querySelectorAll('.end');

                    for (let i = 0; i < elements2.length; i++) {
                        if (!elements2[i].value) {
                            layer.msg('区间不能为空！')
                            return false
                        }

                    }
                }


                let id = GetQueryString('id')
                if (id) {
                    formReloadAjax('/cps/customRechargeTemplate/edit', data.field)

                } else {
                    formReloadAjax('/cps/customRechargeTemplate/add', data.field)

                }

                return false

            });

        });



        // 刷新父页面的局部内容
        function refreshParentPage() {
            // 在这里写入你要进行局部刷新的逻辑

        }

        function removeStage() {

            // 获取所有 class 为 shoudon 的元素
            let elements = document.getElementsByClassName('shoudon');

            // 检查是否至少存在一个元素
            if (elements.length > 0) {
                // 获取最后一个元素
                let lastElement = elements[elements.length - 1];

                // 从 DOM 中移除最后一个元素
                lastElement.parentNode.removeChild(lastElement);
            }
            calculate()
        }

        function addStage(data) {
            let stageHTML = `<div class="stage item shoudon" style="margin-top: 5px;">
                <span>起始-结束集数：</span>
                        <input type="number" value='${data.start}' required="required|nums" style="width: 80px;" class="start layui-input" onchange="checkStage(this)" />-
                        <input type="number" value='${data.end}' required="required|nums" style="width: 80px;" class="end layui-input" onchange="checkStage(this)" />
                        <span style="width: 30px;"></span>
                        <span>收费K币：</span>  <input type="number" required="required|nums" value='${data.pay_amount}' onchange="calculate(true)" style="width: 80px;" class="fee layui-input"  />
                    </div>`
            document.querySelector("#stages").insertAdjacentHTML('beforeend', stageHTML);
        }

        var tagIndex = 1
        function changeTag(index) {

            tagIndex = index
            calculate()
        }

        function fixation() {  //固定K币

            let payamount = $('.payamount').val()
            let rc = JSON.parse(sessionStorage.getItem('recharged_content'))
            let nrc = JSON.parse(sessionStorage.getItem('not_recharged_content'))
            let elements = document.querySelectorAll('.itemtext');
            let strArry = []   //看多少集
            let syArry = []  //剩多少
            let templates = []
            if (nrc) {
                templates = rc.concat(nrc || [])
            } else {
                templates = rc || []
            }



            templates.forEach(item => {
                //    
                var quo = Math.floor(item.sum_currency / payamount);
                var rem = item.sum_currency % payamount;
                syArry.push(rem)
                strArry.push(quo)

            })
            for (let i = 0; i < elements.length; i++) {

                if (templates[i].type == 1 || templates[i].type == 13) {
                    
                    elements[i].innerHTML = `<p>可看${strArry[i]=='Infinity'?0:strArry[i]}集,剩${syArry[i] || 0}K币</p>`;
                } else {
                    elements[i].innerHTML = '';
                }
            }
        }

        function calculate() {
// debugger
            if ($('input[name="charge_type"]:checked').val() == 1) {
                fixation()
                return;
            }

            let stages = document.querySelectorAll('.stage');
            let rc = JSON.parse(sessionStorage.getItem('recharged_content'))
            let nrc = JSON.parse(sessionStorage.getItem('not_recharged_content'))
            let templates = []
            if (nrc) {
                templates = rc.concat(nrc)
            } else {
                templates = rc
            }
            let stageArr = [];
            let templateArr = [];
            let elements = document.querySelectorAll('.itemtext');
            let designated_amount_echo = []

            // 阶梯

            stages.forEach(stage => {
                let start = parseInt(stage.querySelector('.start').value);
                let end = parseInt(stage.querySelector('.end').value);
                let fee = parseInt(stage.querySelector('.fee').value);
                stageArr.push({ start, end, fee });
                designated_amount_echo.push({ start, end, pay_amount: fee })
            });
            $('#interval_recharge').val(JSON.stringify(designated_amount_echo))
            // console.log(designated_amount_echo);
            // 模板
            if (templates) {
                templates.forEach(template => {

                    templateArr.push(template.sum_currency);
                });
            }

            // resultDiv.innerHTML = "";
            let strArry = []   //看多少集
            let syArry = []  //剩多少
            templateArr.forEach((template, i) => {
                let count = 0;
                let fee = template;
                let sy = ''

                stageArr.forEach(stage => {
                    if (fee <= 0) return;
                    // sy = fee % stage.fee;

                    for (let i = stage.start; i <= stage.end; i++) {

                        if (fee - stage.fee >= 0) {
                            fee -= stage.fee;

                            count++;

                        } else {
                            // debugger
                            sy = fee
                            break;
                        }
                        sy = fee - count * stage.fee
                    }
                });
                syArry.push(sy)
                strArry.push(count)

            });

            // let elements = document.querySelectorAll('.itemtext');
            // elements.forEach(element => {
            //     element.innerHTML = '<p>这是新的HTML内容</p>';
            // });
            // debugger
            // if (!bol) {
            //     let val = $('.payamount').val()


            //     for (let i = 0; i < elements.length; i++) {

            //         if (templates[i].type == 1 || templates[i].type == 13) {
            //             let num = parseInt(templates[i].sum_currency / val)

            //             elements[i].innerHTML = `<p>可看${num}集</p>`;

            //         } else {
            //             elements[i].innerHTML = '';
            //         }
            //     }
            //     return;
            // }

            for (let i = 0; i < elements.length; i++) {

                if (templates[i].type == 1 || templates[i].type == 13) {
                    console.log(strArry[i]);
                    elements[i].innerHTML = `<p>可看${strArry[i] || 0}集,剩${syArry[i] || 0}K币</p>`;
                } else {
                    elements[i].innerHTML = '';
                }
            }


        }

        var sylloge;
        function infoSelectN(option, value) {
            if (option.elem == '#pMenu') {

                option.data.forEach(item => {
                    if (item.id == value) {
                        sylloge = item.sylloge
                        $('#jushu').text(sylloge)
                    }
                })
            }
        }

        function onsort(input) {

            var inputElements = document.getElementsByClassName("start");
            if (inputElements.length > 0) {
                inputElements[0].value = input.value;

                calculate()
            }
            // 

        }

        function checkStage(input) {

            let stage = input.parentNode;
            let prevStage = stage.previousElementSibling;
            let starts = document.querySelectorAll('.start');
            let ends = document.querySelectorAll('.end');

            if ($('.sort').val() == '') {
                layer.msg('开始收费剧集不能为空!')
                return
            } else {
                if (parseInt($('.sort').val()) > parseInt(stage.querySelector('.start').value)) {
                    input.value = ''
                    layer.msg('区间开始集数不能小于开始收费剧集!')
                    return
                }
            }

            if (parseInt(input.value) > sylloge) {
                layer.msg('请输入大于当前剧集的集数！当前剧的总集数为：' + sylloge + '集')
                input.value = ''
                return
            }

            if (input.value == '') {
                layer.msg('不能为空')
                return
            }

            //检查输入是否为数字
            if (isNaN(input.value)) {
                layer.msg('请输入数字！')
                input.setCustomValidity("请输入数字");
                return
            } else {
                input.setCustomValidity("");
            }


            //确保结束集数大于开始集数
            if (input.classList.contains('end')) {
                if (parseInt(input.value) <= parseInt(stage.querySelector('.start').value)) {
                    input.value = ''
                    input.setCustomValidity("结束集数需大于开始集数！");
                    layer.msg('结束集数需大于开始集数！')
                    return
                } else {
                    input.setCustomValidity("");
                }
            }

            //检查当前阶梯是否大于前一个阶梯

            if (prevStage && input.classList.contains('start') && parseInt(input.value) <= parseInt(prevStage.querySelector('.end').value)) {
                input.value = ''
                input.setCustomValidity("请输入正确的集数，不能比上个阶梯小！");
                layer.msg('请输入正确的集数，不能比上个阶梯小！')
                return

            } else {
                input.setCustomValidity("");
            }


            interval_recharge.push({
                start: starts,
                end: ends,
                pay_amount: input.value
            })
            calculate()


        }


        // 广告账户ID
        function setInputTag(advertiser_id, disabledAdvertiserId) {
            deleteInputTag()
            $('#advertiser_id').val(advertiser_id.length == 0 ? '' : advertiser_id.toString())

            inputTag({
                elem: '.advertiser_id',
                data: advertiser_id,
                permanentData: disabledAdvertiserId,
                onChange: function (data, value, type) {
                    $('#advertiser_id').val(data.toString())
                }
            })
        }


        function deleteInputTag() {
            $("#advertiser_id").val('')
            $('.fairy-tag-container').children().each(function () {
                if ($(this).hasClass('fairy-tag')) {
                    $(this).remove()
                }
            });
        }
        function add(type) {
            rc = JSON.parse(sessionStorage.getItem('recharged_content'));
            nrc = JSON.parse(sessionStorage.getItem('not_recharged_content'))
            if ((rc?.length == 6 && type == 1) || (nrc?.length == 6 && type == 2)) {
                layer.msg('最多选择6个', {
                    icon: 5
                });
                return false
            }
            let template_number = 0;
            layui.use('form', function () {
                var form = layui.form;
                sessionStorage.setItem('message', JSON.stringify({
                    name: form.val("formAjax").name,
                    type: form.val("formAjax").type
                }))


                if (type === 1) {
                    template_number = rc?.length ?? 0
                } else {
                    template_number = nrc?.length ?? 0
                }
                // x_admin_show('添加充值项', `../recharge/setList.html?type=${type}&template_number=${template_number}`, 1200, 550, null);
            })

            layui.use('layer', function () {
                var layer = layui.layer;

                var index = layer.open({
                    title: "添加充值项",
                    type: 2,
                    area: ['1200px', '550px'],
                    content: `../recharge/setList.html?type=${type}&template_number=${template_number}&token=${token}`,
                    end: function () {
                        // 子弹窗关闭后触发的回调函数r
                        getContent(type);


                    }
                });
            });
        }

        // console.log('id',);
        let id = GetQueryString('id')
        if (id) {
            Ajax(params.detailUrl, { id }).then(result => {
                $("#id").val(result.data.id)
                // 当前详情数据
                let rechargedData = result.data.recharged_content ? result.data.recharged_content : []
                let not_rechargedData = result.data.not_recharged_content ? result.data.not_recharged_content : []
                // 如果缓存有数据 替换
                if (rc) {
                    rechargedData = rc
                }
                if (nrc) {
                    not_rechargedData = nrc
                }
                // sessionStorage.clear()

                if (result.data.sylloge) {
                    sylloge = result.data.sylloge
                    $('#jushu').text(sylloge)
                }

                sessionStorage.setItem('recharged_content', JSON.stringify(rechargedData))
                sessionStorage.setItem('not_recharged_content', JSON.stringify(not_rechargedData))
                sessionStorage.setItem('message', JSON.stringify({
                    name: result.data.name,
                    type: result.data.type,
                    sort: result.data.sort,
                    interval_recharge: result.data.interval_recharge,
                    charge_type: result.data.charge_type,
                    pay_amount: result.data.pay_amount

                }))
                if (result.data.charge_type == 1) {
                    $('.item').hide()
                    $('.guding').show()


                } else {
                    $('.item').show()
                    $('.guding').hide()
                }
                selectParams.selected = [result.data.video_id]
                selectN(selectParams)
                getContent(1)
            });
        } else {


            selectN(selectParams)
            getContent(2)
        }

        function getContent(charge_type) {
            
            $('#recharged_cont').html()
            $('#not_recharged_cont').html()
            // 获取设置的缓存数据
            let recharged_content = sessionStorage.getItem('recharged_content')
            let not_recharged_content = sessionStorage.getItem('not_recharged_content')
            let pay_amount = sessionStorage.getItem('pay_amount')
            let rechargedContent = JSON.parse(recharged_content)
            let not_rechargedContent = JSON.parse(not_recharged_content)
            let datas = JSON.parse(sessionStorage.getItem('message'))?.interval_recharge || []





            layui.use(['form', 'element'], function () {
                var form = layui.form;
                var element = layui.element
                // console.log(JSON.parse( sessionStorage.getItem('message')).interval_recharge);


                setRechargedContent('recharged', rechargedContent, form)
                setRechargedContent('not_recharged', not_rechargedContent, form)
                // if (rechargedContent) {
                //     // 循环创建模板等操作
                //     let rechargedC = ''
                //     let checked = false
                //     rechargedContent.forEach((item, ind) => {
                //         item.checkedName = 'recharged'
                //         item.indexs = ind
                //         let cont = templetContent(item)
                //         rechargedC += cont
                //         if(item.checked == 'checked'){
                //             checked = true
                //         }
                //     })
                //     if(!checked && rechargedContent){
                //         rechargedContent[0]['checked'] = 'checked'
                //     }
                //     $('#recharged_cont').html(rechargedC)
                //     $('#recharged_content').val(JSON.stringify(rechargedContent))
                //     // 单选框事件
                //     form.on('radio(recharged_radio)', function (data) {
                //         rechargedContent.forEach((v, index) => {
                //             if ($(this).attr('data-index') == index) {
                //                 rechargedContent[index].checked = 'checked'
                //             }else{
                //                 rechargedContent[index].checked = ''
                //             }
                //         })
                //         $('#recharged_content').val(JSON.stringify(rechargedContent))
                //         sessionStorage.setItem('recharged_content', JSON.stringify(rechargedContent))
                //     });
                // }

                // if (not_rechargedContent) {
                //     let not_rechargedC = ''
                //     let checked = false
                //     not_rechargedContent.forEach((item, ind) => {
                //         item.checkedName = 'not_recharged'
                //         item.indexs = ind
                //         let cont = templetContent(item)
                //         not_rechargedC += cont
                //         if(item.checked == 'checked'){
                //             checked = true
                //         }
                //     })
                //     if(!checked && not_rechargedContent[0]){
                //         not_rechargedContent[0]['checked'] = 'checked'
                //     }
                //     $('#not_recharged_cont').html(not_rechargedC)
                //     $('#not_recharged_content').val(JSON.stringify(not_rechargedContent))

                //     form.on('radio(not_recharged_radio)', function (data) {
                //         if (not_rechargedContent) {
                //             not_rechargedContent.forEach((v, index) => {
                //                 if ($(this).attr('data-index') == index) {
                //                     not_rechargedContent[index].checked = 'checked'
                //                 }else{
                //                     not_rechargedContent[index].checked = ''
                //                 }
                //             })
                //             $('#not_recharged_content').val(JSON.stringify(not_rechargedContent))
                //             sessionStorage.setItem('not_recharged_content', JSON.stringify(not_rechargedContent))
                //         }
                //     });
                // }
                form.val("formAjax", JSON.parse(sessionStorage.getItem('message')))
                form.render()
                initGridly()
                element.on('tab(tabs)', function () {
                    initGridly()
                });
                if (charge_type == 2) {
                    if ($('input[name="charge_type"]:checked').val() == 2) {
                        
                        calculate()
                    } else {

                        $('.pay_amount').val(pay_amount)

                        fixation()
                    }
                } else {
                    if ($('input[name="charge_type"]:checked').val() == 2) {
                        for (let i = 0; i < datas.length; i++) {
                            const element = datas[i];
                            if (i == 0) {
                                $('.start').val(element.start)
                                $('.fee').val(element.pay_amount)
                                $('.end').val(element.end)
                            } else {

                                addStage(element)
                            }
                        }
                        calculate()
                    } else {

                        $('.pay_amount').val(pay_amount)

                        fixation()
                    }
                }

                // debugger

            })
        }

        //currency  收费K币  sum_currency 总K币 
        function templetContent(params, input) {
            let { id, label, name, original_currency, recharge_price, send_currency, send_title, sum_currency, checked, checkedName, indexs, type } = params

            let typeTemplate = `
                <span class="startSet">
                    ${original_currency}K币
                    ${send_currency ? `<i>+${send_currency}K币</i>` : ''}
                </span>
            `
            let title = `
                <span class='startSet ellipsis' style='color:#f0ca23'>
                    ${send_title}    
                </span>
            `
            return `<div class="layui-col-xs12 layui-col-md6 brick" style='height:150px' data-message=${JSON.stringify(params)} data-session_name=${checkedName}>
                        <div class="moneyContent">
                            <div class="content">
                                <div>
                                    <span class="title">${name}</span>
                                    <span class="tip" style='${type != 1 ? 'background-color:#f0ca23' : ''}'>${label}</span>
                                </div>
                                <div>
                                    ${type == 1 ? typeTemplate : title}
                                </div>
                            </div>
                            <div class="foot">
                                <!-- <input type="radio" lay-filter="${checkedName}_radio" data-indexs='${indexs}' name="${checkedName}_checked" value="${id}" title="默认勾选" ${checked ? checked : ''}> -->
                               <div class='itemtext'></div>
                                <div>
                                    <!-- <i class="layui-icon layui-icon-set-sm setting" style="font-size: 20px;font-weight:bold" data-indexs='${indexs}' data-type='${checkedName}'></i> -->
                                    <i class="layui-icon layui-icon-edit edit" style="font-size: 24px;" data-params='${JSON.stringify(params)}' data-type='${checkedName}_content' data-indexs='${indexs}'></i>
                                    <i class="layui-icon layui-icon-delete delete" style="font-size: 24px;" data-type='${checkedName}_content' data-indexs='${indexs}' ></i>
                                </div>
                            </div>
                        </div>
                    </div>`
        }
        // 删除
        $("body").on("click", ".delete", function () {

            let type = $(this).attr('data-type')
            let template_index = JSON.parse($(this).attr('data-indexs'))
            let temContent = JSON.parse(sessionStorage.getItem($(this).attr('data-type')))
            let now_index = 0;
            temContent.forEach((v, index) => {
                if (template_index == v.indexs) {
                    now_index = index
                }
            })
            layer.confirm('确认要删除吗？', function (layMask) {
                let rc = JSON.parse(sessionStorage.getItem('recharged_content'))
                let nrc = JSON.parse(sessionStorage.getItem('not_recharged_content'))
                type == 'recharged_content' ? rc.splice(now_index, 1) : nrc.splice(now_index, 1)

                if (temContent[now_index].checked == 'checked') {
                    if (type == 'recharged_content') {
                        rechargedIndex = 0
                        if (rc[0]) {
                            rc[0].checked = 'checked'
                        }
                    } else {
                        not_rechargedIndex = 0
                        if (nrc[0]) {
                            nrc[0].checked = 'checked'
                        }
                    }
                }

                sessionStorage.setItem(type, JSON.stringify(type == 'recharged_content' ? rc : nrc))
                getContent(2)
                layer.close(layMask);
            });
        });
        // 修改
        $("body").on("click", ".edit", function () {
            let params = JSON.parse($(this).attr('data-params'))
            let template_index = $(this).attr('data-indexs')
            let temContent = JSON.parse(sessionStorage.getItem($(this).attr('data-type')))

            layui.use(["form", "layer"], function () {
                $ = layui.jquery;
                var form = layui.form,
                    layer = layui.layer;
                layer.open({
                    type: 1,
                    title: '编辑',
                    btn: ['保存', '取消'],
                    maxHeight: '500',
                    content: `
                        <div class="x-body moneyTemplate">
                            <blockquote class="layui-elem-quote" style="border-color:#ff5722;color: #db552b;">请勿输入特殊符号！</blockquote>
                            <form class="layui-form editTemplate" lay-filter="editTemplate">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">
                                        <span class="x-red">*</span>名称
                                    </label>
                                    <div class="layui-input-block">
                                        <input type="text" name="name" id="money_name" placeholder="名称" required="required"  lay-verify="required|ZnNum" autocomplete="off" class="layui-input verifyZnNum" value="" />
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">
                                        <span class="x-red">*</span>充值金额(元)
                                    </label>
                                    <div class="layui-input-block">
                                        <input type="text" name="recharge_price" id="recharge_price" placeholder="充值金额" required="required"
                                            lay-verify="required" autocomplete="off" class="layui-input" value="" />
                                    </div>
                                </div>
                                ${params.type == 1 ?
                            `
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">
                                            <span class="x-red">*</span>充值K币
                                        </label>
                                        <div class="layui-input-block">
                                            <input type="text" name="original_currency" id="original_currency" placeholder="充值K币" disabled autocomplete="off" class="layui-input " value="" />
                                        </div>
                                    </div>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">
                                            <span class="x-red">*</span>赠送K币
                                        </label>
                                        <div class="layui-input-block">
                                            <input type="number" name="send_currency" id="send_currency" placeholder="赠送K币" required="required"
                                                lay-verify="required|num" autocomplete="off" class="layui-input verifyNum" value="" pattern="^[0-9]*$" />
                                        </div>
                                    </div>`
                            :
                            `<div class="layui-form-item">
                                        <label class="layui-form-label">
                                            <span class="x-red">*</span>赠送标语
                                        </label>
                                        <div class="layui-input-block">
                                            <input type="text" name="send_title" id="send_title" placeholder="赠送标语" required="required"
                                                lay-verify="required|ZnNum" autocomplete="off" class="layui-input verifyZnNum" value="" />
                                        </div>
                                    </div>`
                        }
                                
                                <div class="layui-form-item">
                                    <label class="layui-form-label">
                                        标签
                                    </label>
                                    <div class="layui-input-block">
                                        <input type="text" name="label" id="label" placeholder="标签"
                                            lay-verify="ZnNum" autocomplete="off" class="layui-input verifyZnNum" value="" />
                                    </div>
                                </div>
                                
                                <input type="hidden" name="id" id="id" value="" />
                                <input type="hidden" name="indexs" value="" />
                                <input type="hidden" name="checkedName" value="" />
                                <button id="submitTemplate" class="layui-btn" lay-submit lay-filter="submitTemplate"  lay-on="get-jy" style="display: none;" />
                                
                            </form>
                        </div>
                    `,
                    yes: function (layMask) {
                        let data = form.val("editTemplate")
                        let now_template = {};
                        temContent.forEach((v, index) => {
                            if (template_index == v.indexs) {
                                now_template = temContent[index]
                            }
                        })

                        if ($("#money_name").val() == '') {
                            layer.msg('名称不能为空！', { icon: 5, time: 2000 })
                            return;
                        }
                        if (Number($("#recharge_price").val()) <= 0) {
                            layer.msg('金额不能为0！', { icon: 5, time: 2000 })
                            return;
                        }

                        layui.use('form', function () {
                            var form = layui.form;
                            form.verify({
                                ZnNum: function (value, item) { //value：表单的值、item：表单的DOM对象
                                    // var patter_special_char = /[,;；，"’'`·《》[\\]]+/;
                                    // if(value.match(patter_special_char) != null){
                                    //     return '请勿输入特殊符号！';
                                    // }
                                    var regEn = /[`!@#$%^&*()_<>?:"{}\/;'[\]]/im,
                                        regCn = /[·！#￥（——）：；“”‘|《。》？【】[\]]/im;
                                    if (regEn.test(value) || regCn.test(value)) {
                                        return '请勿输入特殊符号！';
                                    }
                                }
                                , num: [
                                    /^[0-9]*$/
                                    , '只能输入数字！'
                                ]
                            });
                        });
                        if (form.validate('.editTemplate')) {
                            // temContent.forEach((v,i)=>{
                            //     if(Number(v.id) === Number(data.id)){
                            //         Object.keys(data).forEach((item,index)=>{
                            //             v[item] = Object.values(data)[index]
                            //         })
                            //         v.sum_currency = Number(v.original_currency) + Number(v.send_currency)
                            //     }
                            // })
                            Object.keys(data).forEach((item, index) => {
                                now_template[item] = Object.values(data)[index]
                            })
                            now_template.sum_currency = Number(now_template.original_currency) + Number(now_template.send_currency)
                            sessionStorage.setItem(data.checkedName + '_content', JSON.stringify(temContent))
                            $('#' + data.checkedName + '_content').val(JSON.stringify(temContent))
                            getContent(2)
                            layer.close(layMask)
                        }

                    }
                });
                form.val("editTemplate", params);
                $("#recharge_price").on('input propertychange', function (e) {
                    $("#original_currency").val((clearNoNum($(this)) * 100).toFixed())
                })
            });

        });
        // 设置
        $("body").on("click", ".setting", function () {
            let type = $(this).attr('data-type') == 'recharged' ? 1 : 2
            let index = $(this).attr('data-indexs')
            sessionStorage.setItem(type + '_index', index)
            x_admin_show('修改充值项', `../recharge/setList.html?type=${type}&seting=${index}`, 1200, 550, null);
        });

        function clearNoNum(that) {
            let num = that.val()
            num = num.replace(/[^\d.]/g, "");  //清除“数字”和“.”以外的字符   
            num = num.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的   
            num = num.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
            num = num.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');//只能输入两个小数   
            if (num.indexOf(".") < 0 && num != "") {
                num = parseFloat(num);
            }
            that.val(num)
            return num
        }



        // Ajax(selectParams.url, { id }).then(result => {
        //     selectParams.selected = [result.data.video_id]
        //     selectN(selectParams)
        // });

        // 设置拖拽
        function initGridly() {
            if (!phone) {
                $('.gridly').gridly({
                    base: 64, // px 
                    gutter: 8, // px
                    columns: 12,
                    callbacks: { reordered }  //拖拽后回调函数
                });
            }
        }
        var reordered = function ($elements) {
            //当前拖拽对象
            var currentObj = this.reordered.arguments[1];
            if (typeof (currentObj) != "undefined") {
                //拖拽后模块数组
                var arr = $elements;
                let message = []
                let session_name = ''

                arr.each((index, item) => {
                    let message_item = $(item).data('message');
                    let nowIndex = $(item).data('session_name') == 'recharged' ? rechargedIndex : not_rechargedIndex;
                    message_item.checked = ''
                    message.push(message_item)
                    session_name = $(item).data('session_name')
                    if (index == 0) {
                        message_item.checked = 'checked'
                    } else {
                        message_item.checked = ''
                    }
                })
                sessionStorage.setItem(session_name + '_content', JSON.stringify(message))
                $('#' + session_name + '_content').val(JSON.stringify(message))

            }
        }
        // var itemVarr = []
        // 创建模板
        function setRechargedContent(name, content, form) {
            var itemVarr = []
            if (content) {
                // 循环创建模板等操作
                let rechargedC = ''
                let checked = false
                content.forEach((item, ind) => {

                    item.checkedName = name
                    item.indexs = ind
                    itemVarr.push(item)
                    let cont = templetContent(item)
                    rechargedC += cont
                    if (item.checked == 'checked') {
                        checked = true
                    }
                    item.checked = ''
                })
                if (content[0]) {
                    content[0]['checked'] = 'checked'
                }
                $(`#${name}_cont`).html(rechargedC)
                $(`#${name}_content`).val(JSON.stringify(content))
                sessionStorage.setItem(`${name}_content`, JSON.stringify(content))
                // 单选框事件
                form.on(`radio(${name}_radio)`, function (data) {
                    let this_index = $(this).parent().parent().parent().index();
                    let conts = JSON.parse(sessionStorage.getItem(`${name}_content`))
                    let data_index = $(this).attr('data-indexs')
                    conts.forEach((v, index) => {
                        conts[0].checked = 'checked';
                    })
                    $(`#${name}_content`).val(JSON.stringify(conts))
                    sessionStorage.setItem(`${name}_content`, JSON.stringify(conts))
                });
            }
        }

        $("body").on("keypress", "input", function (e) {
            if (e.which === 32 || e.which == 13) {
                return false;
            }
        });
    </script>

</body>

</html>